package com.Java.cs;

import java.io.*;

public class UserServiceImpl implements UserService {

    @Override
    public boolean register(User user) {
        String fileName = user.getName() + ".txt";

        try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileName))) {
            writer.write("name=" + user.getName() + "\n");
            writer.write("username=" + user.getUsername() + "\n");
            writer.write("password=" + user.getPassword());
            return true; // 注册成功
        } catch (IOException e) {
            e.printStackTrace();
            return false; // 注册失败
        }
    }

    @Override
    public boolean login(String username, String password) {
        String fileName = username + ".txt"; // 假设文件名即为用户名

        try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
            String line;
            String fileUsername = null;
            String filePassword = null;

            while ((line = reader.readLine()) != null) {
                if (line.startsWith("username=")) {
                    fileUsername = line.substring("username=".length()); // 获取用户名
                } else if (line.startsWith("password=")) {
                    filePassword = line.substring("password=".length()); // 获取密码
                }
            }

            // 比较读取的用户名和密码是否与输入相同
            return username.equals(fileUsername) && password.equals(filePassword);
        } catch (IOException e) {
            e.printStackTrace();
            return false; // 登录失败或文件未找到
        }
    }
}